package cn.waka.sys.admin.controller;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.waka.sys.admin.object.Result;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {
    /*
        @Autowired
        private FileUploadService uploadService;
        */
    @RequestMapping(value = "upload", method = RequestMethod.POST, produces = "application/json; charset=UTF-8", name = "文件上传")
    public Result upload(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            String fname = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes()) + "." + ext;
            URL ppath = Thread.currentThread().getContextClassLoader().getResource("/static");
            String path = ppath.getPath() + fname;
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
                //String location = uploadService.upload("admin/upload/" + fname, path);


                Map<String, String> data = new HashMap<String, String>(1);
                data.put("path", path);
                return ok(data);
            } catch (Exception e) {
                e.printStackTrace();
                return error(-500, e.getMessage());
            } finally {
                FileUtils.deleteQuietly(new File(path));

            }
        } else {
            return error(-500, "文件为空");
        }
    }
}
